package rua.jose.macamo;

/**
 * LocationList class handles the menu list showing the locations
 */

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class LocationList extends ListActivity {
   private ArrayList<mOverlayItem> locations = null;
   private LocationAdapter adapter;


   @Override
   public void onCreate(final Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.locationslist);
      locations = getIntent().getParcelableArrayListExtra("items");
      this.adapter = new LocationAdapter(this, R.layout.row, locations);
      setListAdapter(this.adapter);
      final EditText tv = (EditText) findViewById(R.id.entry);

      tv.addTextChangedListener(new TextWatcher() {

         @Override
         public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
            adapter.getFilter().filter(s);
         }

         @Override
         public void beforeTextChanged(final CharSequence s, final int start, final int count,
               final int after) {}

         @Override
         public void afterTextChanged(final Editable s) {}
      });

      final Bundle b = getIntent().getExtras(); //Get the bundle passed by the launching activity
      final String keyword = b.getString("search"); //Get possible search keyword
      adapter.notifyDataSetChanged();
      if (keyword != null)
         adapter.getFilter().filter(keyword);
   }

   @Override
   public void onListItemClick(final ListView l,final View v,final int position,final long id){
      final CharSequence[] items = {"Show on map","Show info"};
      final AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setTitle("Select an option");

      builder.setItems(items, new DialogInterface.OnClickListener() {
         public void onClick(final DialogInterface dialog, final int i) {
            if(i == 0){
               setResult(locations.indexOf(locations.get(position)));
               System.gc();
               finish();
            }
            else{
               final Intent intent = new Intent(LocationList.this, LocationInfo.class);
               final Bundle b = new Bundle();
               b.putParcelable("item", locations.get(position));
               intent.putExtras(b);
               startActivity(intent);
            }
         }
      });

      final AlertDialog alert = builder.create();
      alert.show();

   }

   @Override
   public boolean onKeyDown(final int keyCode, final KeyEvent msg) {
      if(keyCode == KeyEvent.KEYCODE_BACK) {
         setResult(Constant.BACK);
         finish();
      }
      return true;
   }

   public boolean onKeyUp(final int keyCode, final KeyEvent msg) {
      return true;
   }
}

class LocationAdapter extends ArrayAdapter<mOverlayItem> {
   protected final ArrayList<mOverlayItem> items, filtered;
   protected Filter filter;
   private final Context context;



   public LocationAdapter(final Context context, final int textViewResourceId, final ArrayList<mOverlayItem> items) {
      super(context, textViewResourceId, items);
      this.context = context;
      this.filtered = items;
      this.items = new ArrayList<mOverlayItem>(filtered);
      this.filter =  new NameFilter();
   }

   @Override
   public View getView(final int position, final View convertView, final ViewGroup parent) {
      View v = convertView;


      if (v == null) {
         final LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         v = vi.inflate(R.layout.row, null);
      }
      final mOverlayItem o = filtered.get(position);


      if (o != null) {
         final ImageView it = (ImageView) v.findViewById(R.id.list_icon);
         if(it != null){
            it.setImageResource(context.getResources().getIdentifier("drawable/"+o.type, null, context.getPackageName()));
         }
         final TextView tt = (TextView) v.findViewById(R.id.list_text);
         if (tt != null) {
            tt.setText(o.getTitle());
         }
      }
      return v;
   }

   public Filter getFilter() {
      if(filter == null)
         filter = new NameFilter();
      return filter;
   }

   private class NameFilter extends Filter {
      @Override
      protected FilterResults performFiltering(CharSequence constraint) {
         constraint = constraint.toString().toLowerCase();
         final FilterResults result = new FilterResults();
         if(constraint != null && constraint.toString().length() > 0) {
            final ArrayList<mOverlayItem> filt = new ArrayList<mOverlayItem>();
            final ArrayList<mOverlayItem> lItems = new ArrayList<mOverlayItem>();
            synchronized (this) {
               lItems.addAll(items);
            }
            for (final mOverlayItem m : lItems) {
               if(m.getTitle().toLowerCase().contains(constraint))
                  filt.add(m);
            }
            result.count = filt.size();
            result.values = filt;
         }
         else {
            synchronized(this) {
               result.values = items;
               result.count = items.size();
            }
         }
         return result;
      }

      @SuppressWarnings("unchecked")
      @Override
      protected void publishResults(final CharSequence constraint, final FilterResults results) {
         filtered.clear();
         filtered.addAll((ArrayList<mOverlayItem>)results.values);
         notifyDataSetChanged();
         notifyDataSetInvalidated();
      }
   }
}